package cn.touna.jss.modules.custom.carloan;

import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.risk.api.utils.JSONUtil;
import cn.touna.jss.common.factory.ResponseFactory;
import cn.touna.jss.common.util.ValidUtil;
import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.custom.carloan.entity.TrafficViolationEntity;
import cn.touna.jss.modules.third.telecredit.TelecreditService;
import cn.touna.jss.modules.third.tx.TianXingService;
import cn.touna.risk.api.domain.Response;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;


/**
 * 车贷系统交通相关服务
 * Created by wuwc
 */
@Service
public class TrafficService {
    private static final Logger logger = LogManager.getLogger(TrafficService.class);

    @Autowired
    private TianXingService tianXingService;

    @Autowired
    private TelecreditService telecreditService;

    /**
     * 交通违规查询
     *
     * @param request
     * @return
     */
    @ApiMapping(value = "traffic.violation",desc = "复合接口.交通违章记录(泰尔英福/天行)")
    public Response trafficViolation(TrafficViolationEntity violationEntity) {
        ValidUtil.checkRequestParams(violationEntity);
        JSONObject result = new JSONObject();
        BigDecimal totalCount = BigDecimal.ZERO;
        BigDecimal totalDegree = BigDecimal.ZERO;
        int totalNum = 0;
        try {
            Response telecreditRsp = telecreditService.trafficViolation(violationEntity);
            logger.info("泰尔英福返回结果,result:{}", telecreditRsp);
            if (telecreditRsp != null && telecreditRsp.checkIfSuccess()) {
                JSONArray jsonArray = JSONUtil.getJSONArray(telecreditRsp.getData().toString(), "records", new JSONArray());
                totalNum = jsonArray.size();
//                result.put("totalNum", jsonArray.size());
                JSONArray recordJsonArry = new JSONArray();
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    boolean status = JSONUtil.getBoolean(jsonObject, "status", false);
                    if (!status) {
                        BigDecimal countDecimal = new BigDecimal(JSONUtil.getString(jsonObject, "count", "0.0"));
                        BigDecimal degreeDecimal = new BigDecimal(JSONUtil.getString(jsonObject, "Degree", "0.0"));
                        totalCount = totalCount.add(countDecimal);
                        totalDegree = totalDegree.add(degreeDecimal);
                    }
                    JSONObject recordJson = new JSONObject();
                    recordJson.put("time", JSONUtil.getString(jsonObject, "Time", null));
                    String location = JSONUtil.getString(jsonObject, "LocationName", "")
                            .concat(JSONUtil.getString(jsonObject, "Location", ""));
                    recordJson.put("location", location);
                    recordJson.put("reason", JSONUtil.getString(jsonObject, "Reason", null));
                    recordJson.put("count", JSONUtil.getString(jsonObject, "count", null));
                    recordJson.put("status", JSONUtil.getString(jsonObject, "status", null));
                    recordJson.put("degree", JSONUtil.getString(jsonObject, "Degree", null));
                    recordJson.put("code", JSONUtil.getString(jsonObject, "Code", null));
                    recordJsonArry.fluentAdd(recordJson);
                }
                result.put("records", recordJsonArry);
            } else {
                Response txRsp = tianXingService.trafficOffences(violationEntity);
                if (txRsp.checkIfSuccess()) {
                    boolean hasData = JSONUtil.getBoolean(txRsp.getData().toString(), "hasData", false);
                    if (hasData) {
                        JSONArray jsonArray = JSONUtil.getJSONArray(txRsp.getData().toString(), "records", null);
//                        result.put("totalNum", jsonArray.size());
                        totalNum = jsonArray.size();
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            boolean status = JSONUtil.getBoolean(jsonObject, "status", false);
                            //只累计未处理
                            if (!status) {
                                BigDecimal countDecimal = new BigDecimal(jsonObject.getString("count"));
                                BigDecimal degreeDecimal = new BigDecimal(jsonObject.getString("degree"));
                                totalCount = totalCount.add(countDecimal);
                                totalDegree = totalDegree.add(degreeDecimal);
                            }
                        }
                        result.put("records", jsonArray);
                    }
                }
            }
            result.put("totalNum",totalNum);
            result.put("totalCount", totalCount.doubleValue());
            result.put("totalDegree", totalDegree.doubleValue());
            result.put("carNumber", violationEntity.getCarNumber());
            return ResponseFactory.success(result);
        } catch (Exception e) {
            logger.error("REE 【交通违规查询】异常,params:{}，msg:{}", violationEntity, e.getMessage());
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_SYSTEM_ERROR, e.getMessage());
        }
    }

}
